package com.dpiinc.TechPage.video;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.FileProvider;

import com.dpiinc.TechPage.AIWriteApplication;
import com.dpiinc.TechPage.R;
import com.dpiinc.TechPage.user.utils.ToastUtils;
import com.dpiinc.TechPage.widget.CirclePgBar;
import com.dpiinc.TechPage.widget.VideoProgressView;
import com.beiji.lib.pen.model.PenStroke;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.system.email.Email;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by hu489_000 on 2018-07-14.
 */

public class ShareVideoHelper {
    public static final String TAG = "ShareVideoHelper";
    private static String type = null;
    private static Context mcontext;

    public static void showShareDialog(Context context, final ArrayList<PenStroke> list, Boolean isTen,final int width) {
        mcontext = context;
        final Context finalMcontext = mcontext;
        final Dialog bottomDialog = new Dialog(mcontext, R.style.BottomDialog);
        View contentView = LayoutInflater.from(mcontext).inflate(R.layout.share_video_pop, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = mcontext.getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.show();

        View share_wechat = (View) contentView.findViewById(R.id.share_wechat);
        share_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = Wechat.NAME;
                CirclePgBar circlePgBar = VideoProgressView.createLoadingViewAndShow(finalMcontext, 0);
                bottomDialog.dismiss();
                StrokeToBitmap.getInstance().drawStrokesTenSecond(getStrokeList(list), finalMcontext, circlePgBar,width)
                ;
            }
        });
        View share_wechat_time = (View) contentView.findViewById(R.id.share_wechat_time);
        share_wechat_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = WechatMoments.NAME;
                CirclePgBar circlePgBar = VideoProgressView.createLoadingViewAndShow(finalMcontext, 0);
                bottomDialog.dismiss();
                StrokeToBitmap.getInstance().drawStrokesTenSecond(getStrokeList(list), finalMcontext, circlePgBar,width);
            }
        });
        View share_qq = (View) contentView.findViewById(R.id.share_qq);
        share_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = QQ.NAME;
                CirclePgBar circlePgBar = VideoProgressView.createLoadingViewAndShow(finalMcontext, 0);
                bottomDialog.dismiss();
                StrokeToBitmap.getInstance().drawStrokesTenSecond(getStrokeList(list), finalMcontext, circlePgBar,width);
            }
        });
        View share_weibo = (View) contentView.findViewById(R.id.share_weibo);
        share_weibo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = SinaWeibo.NAME;
                CirclePgBar circlePgBar = VideoProgressView.createLoadingViewAndShow(finalMcontext, 0);
                bottomDialog.dismiss();
                StrokeToBitmap.getInstance().drawStrokesTenSecond(getStrokeList(list), finalMcontext, circlePgBar,width);
            }
        });
        View share_email = (View) contentView.findViewById(R.id.share_email);
        share_email.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = Email.NAME;
                CirclePgBar circlePgBar = VideoProgressView.createLoadingViewAndShow(finalMcontext, 0);
                bottomDialog.dismiss();
                StrokeToBitmap.getInstance().drawStrokesTenSecond(getStrokeList(list), finalMcontext, circlePgBar,width);
            }
        });
        View share_normal = (View) contentView.findViewById(R.id.share_normal_video);
        share_normal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = null;
                CirclePgBar circlePgBar = VideoProgressView.createLoadingViewAndShow(finalMcontext, 0);
                bottomDialog.dismiss();
                StrokeToBitmap.getInstance().drawStrokesUntilProgress(getStrokeList(list), finalMcontext, circlePgBar,width);
            }
        });
        if (isTen) {
            View share_ten = (View) contentView.findViewById(R.id.share_ten);
            share_ten.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    type = null;
                    CirclePgBar circlePgBar = VideoProgressView.createLoadingViewAndShow(finalMcontext, 0);
                    bottomDialog.dismiss();
                    StrokeToBitmap.getInstance().drawStrokesTenSecond(getStrokeList(list), finalMcontext, circlePgBar,width);
                }
            });
        } else {
            ImageView iv_tenvideo = contentView.findViewById(R.id.iv_tenvideo);
            iv_tenvideo.setImageDrawable(mcontext.getResources().getDrawable(R.drawable.share_ten_unuse));
            TextView tv_tenvideo = contentView.findViewById(R.id.tv_tenvideo);
            tv_tenvideo.setTextColor(mcontext.getResources().getColor(R.color.connect_pen_tip_low_battery));
        }
    }

    private static void showGuideDialog() {
        View view = View.inflate(mcontext, R.layout.select_platform, null);
        View btnConnect = view.findViewById(R.id.btn_go_share);
        View btnClose = view.findViewById(R.id.btn_close);
        TextView tv_text = view.findViewById(R.id.tv_text_2);
        if (type == null) {
            ToastUtils.showCenterTip(mcontext, AIWriteApplication.Companion.instance().getResources().getString(R.string.video_save_success));
            return;
        }
        if (type.equals(Wechat.NAME) || type.equals(WechatMoments.NAME)) {
            tv_text.setText(AIWriteApplication.Companion.instance().getResources().getString(R.string.open_wechat_share));
        } else if (type.equals(QQ.NAME)) {
            tv_text.setText(AIWriteApplication.Companion.instance().getResources().getString(R.string.open_qq_share));
        } else if (type.equals(SinaWeibo.NAME)) {
            tv_text.setText(AIWriteApplication.Companion.instance().getResources().getString(R.string.open_weibo_share));
        } else if (type.equals(Email.NAME)) {
            tv_text.setText(AIWriteApplication.Companion.instance().getResources().getString(R.string.open_email_share));
        }
        final AlertDialog newUserGuideDialog = new AlertDialog.Builder(mcontext)
                .setView(view)
                .create();
        btnConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                ComponentName cmp = null;
                if (type != null) {
                    if (type.equals(Wechat.NAME) || type.equals(WechatMoments.NAME)) {
                        if (isAvilible(mcontext, "com.tencent.mm")) {
                            cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                            intent.setAction(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_LAUNCHER);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setComponent(cmp);
                            mcontext.startActivity(intent);
                        } else {
                            ToastUtils.showCenterTip(mcontext, AIWriteApplication.Companion.instance().getResources().getString(R.string.download_wechat_first));
                            return;
                        }
                    } else if (type.equals(QQ.NAME)) {
                        try {
                            Intent intents = mcontext.getPackageManager().getLaunchIntentForPackage("com.tencent.mobileqq");
                            mcontext.startActivity(intents);
                        } catch (Exception e) {
                            ToastUtils.showCenterTip(mcontext, AIWriteApplication.Companion.instance().getResources().getString(R.string.download_qq_first));
                            e.printStackTrace();
                        }
                    } else if (type.equals(SinaWeibo.NAME)) {
                        try {
                            Intent intents = mcontext.getPackageManager().getLaunchIntentForPackage("com.sina.weibo");
                            mcontext.startActivity(intents);
                        } catch (Exception e) {
                            ToastUtils.showCenterTip(mcontext, AIWriteApplication.Companion.instance().getResources().getString(R.string.download_weibo_first));
                            e.printStackTrace();
                        }
                    } else if (type.equals(Email.NAME)) {
                        // 必须明确使用mailto前缀来修饰邮件地址,如果使用
// intent.putExtra(Intent.EXTRA_EMAIL, email)，结果将匹配不到任何应用
                        Uri uri = Uri.parse("mailto:3802**92@qq.com");
                        String[] email = {"3802**92@qq.com"};
                        Intent intents = new Intent(Intent.ACTION_SENDTO, uri);
                        intents.putExtra(Intent.EXTRA_CC, email); // 抄送人
                        intents.putExtra(Intent.EXTRA_SUBJECT, AIWriteApplication.Companion.instance().getResources().getString(R.string.email_theme)); // 主题
                        intents.putExtra(Intent.EXTRA_TEXT, AIWriteApplication.Companion.instance().getResources().getString(R.string.email_content)); // 正文
                        mcontext.startActivity(Intent.createChooser(intents, AIWriteApplication.Companion.instance().getResources().getString(R.string.choose_email_application)));
                    }

                } else {
                    ToastUtils.showCenterTip(mcontext, AIWriteApplication.Companion.instance().getResources().getString(R.string.video_save_success));
                }
                newUserGuideDialog.dismiss();
            }
        });
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                newUserGuideDialog.dismiss();
            }
        });
        newUserGuideDialog.show();
    }

    public static void ChangeSuccess(final String path) {
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                if (path != null) {
                    showGuideDialog();
                    updateVideo(path);
                    shareAudio(path);
//                    AlbumNotifyHelper.insertVideoToMediaStore(mcontext,path,0,0);
                } else {
                    ToastUtils.showCenterTip(mcontext, AIWriteApplication.Companion.instance().getResources().getString(R.string.video_save_fail));
                }
            }
        });
    }

    private static void shareAudio(String path) {
        File file = new File(path);
        Uri uri = FileProvider.getUriForFile(mcontext, "com.dpiinc.TechPage.provider", file);
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("video/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        Intent chooser = Intent.createChooser(intent, "share:");
        mcontext.startActivity(chooser);

/*        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        File file = new File(path);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(mcontext, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            intent.setDataAndType(contentUri, "video/*");
            mcontext.startActivity(intent);
        } else {
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "video/*");
            mcontext.startActivity(intent);
        }*/
    }

    /**
     * 分享音乐
     */
/*
    private fun shareAudio(file: File) {
        if (file.exists()) {
            val uri = FileProvider.getUriForFile(context, "com.xincore.tech.app.provider", file)
            val intent = Intent()
            intent.action = Intent.ACTION_SEND
            intent.type = "audio/*"
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            val chooserIntent = Intent.createChooser(intent, "分享到:")
            context.startActivity(chooserIntent)
        } else {
            Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show()
        }
    }
*/

//    private static void uploadVideoLoacl(String path) {//通知本地相册刷新
//        ContentValues localContentValues = new ContentValues();
//        localContentValues.put(MediaStore.Video.Media.DATA, getFileName(path));
//        localContentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
//        ContentResolver localContentResolver = mcontext.getContentResolver();
//        Uri localUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
//        localContentResolver.insert(localUri, localContentValues);
//    }

    /*** 将视频插入图库* @param url 视频路径地址*/
    private static void updateVideo(String url) {
        File file = new File(url); //获取ContentResolve对象，来操作插入视频
        ContentResolver localContentResolver = mcontext.getContentResolver(); //ContentValues：用于储存一些基本类型的键值对
        ContentValues localContentValues = getVideoContentValues( file, System.currentTimeMillis());//insert语句负责插入一条新的纪录，如果插入成功则会返回这条记录的id，如果插入失败会返回-1。
        Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
//        Toast.makeText(mcontext, localUri.toString(), Toast.LENGTH_SHORT).show();
    }

    private static ContentValues getVideoContentValues(File paramFile, long paramLong) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", paramFile.getName());
        localContentValues.put("_display_name", paramFile.getName());
        localContentValues.put("mime_type", "video/mp4");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        localContentValues.put("_data", paramFile.getAbsolutePath());
        localContentValues.put("_size", Long.valueOf(paramFile.length()));
        return localContentValues;
    }

    private static String getFileName(String pathandname) {
        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }
    }

    private static boolean isAvilible(Context mcontext, String packagename) {
        final PackageManager packageManager = mcontext.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals(packagename)) {
                    return true;
                }
            }
        }
        return false;
    }

    private static ArrayList<PenStroke> getStrokeList(ArrayList<PenStroke> list) {
        ArrayList<PenStroke> penStrokes = new ArrayList<>();
        penStrokes.addAll(list);
        return penStrokes;
    }
}
